package com.cirnoworks.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

@Singleton
public class Hasher {

	private final ThreadLocal<MessageDigest> encoder;

	@Inject
	public Hasher(@Named("uhs.hash.method") final String method) {
		encoder = new ThreadLocal<MessageDigest>() {
			protected synchronized MessageDigest initialValue() {
				try {
					return MessageDigest.getInstance(method);
				} catch (NoSuchAlgorithmException e) {
					throw new RuntimeException(e);
				}
			}
		};
	}

	public byte[] encode(String str) {
		try {
			byte[] ret = encoder.get().digest(str.getBytes("utf-8"));
			if (ret.length < 32) {
				byte[] tmp = ret;
				ret = new byte[32];
				System.arraycopy(tmp, 0, ret, 0, tmp.length);
			} else if (ret.length > 32) {
				byte[] tmp = ret;
				ret = new byte[32];
				System.arraycopy(tmp, 0, ret, 0, 16);
			}
			return ret;
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}
